import {
  _decorator,
  Component,
  Node,
  Vec3,
  tween,
  Tween,
  AudioClip,
  AudioSource,
  resources,
  sys,
  Label
} from 'cc';

const { ccclass, property } = _decorator;
import { GlobalEvent } from '../events/GlobalEvent';
import { EventTypes } from '../events/EventTypes';
import { UserModel } from '../models/user';
import { ENV } from '../config/main';
import { TaKuSDK } from '../TaKuSDK';

@ccclass('ShakeButton')
export class ShakeButton extends Component {
  @property({ tooltip: "点击音效路径（resources 相对路径）" })
  soundPath: string = 'audio/DefaultClick.mp3';

  @property({ tooltip: "是否启用点击音效" })
  enableSound: boolean = true;

  @property({ tooltip: "是否启用点击缩放动画" })
  enableClickScale: boolean = true;


  // 按钮node
  @property(Node)
  buttonNode: Node = null;

  // 倒计时label
  @property(Label)
  countdownLabel: Label = null;

  private audioClip: AudioClip | null = null;
  private audioSource: AudioSource | null = null;
  private shakeTween: Tween<Node> | null = null;


  private countdown: number = 30; //默认倒计时30秒
  @property
  private maxCountdown: number = 30; // 最大倒计时时间
  private timerCallback = null;

  onLoad() {
      // 添加 AudioSource（若无）
      // this.audioSource = this.node.getComponent(AudioSource);
      // if (!this.audioSource) {
      //     this.audioSource = this.node.addComponent(AudioSource);
      // }

      // 播放摇摆动画
      this.startShake();

      // 绑定点击事件
      this.buttonNode.on(Node.EventType.TOUCH_END, this.onClick, this);


      GlobalEvent.on(EventTypes.REWARD_VIDEO_AD_PLAY_END, this.videoPlayEnd, this);
  }

  onDestroy() {
      this.stopShake();
      this.buttonNode.off(Node.EventType.TOUCH_END, this.onClick, this);
      this.stopCountdown();

      GlobalEvent.off(EventTypes.REWARD_VIDEO_AD_PLAY_END, this.videoPlayEnd, this);
  }

  private onClick() {
    
    console.log("点击按钮");
    if (this.enableClickScale) {
        tween(this.node)
            .to(0.05, { scale: new Vec3(0.9, 0.9, 1) })
            .to(0.05, { scale: new Vec3(1, 1, 1) })
            .start();
    }

    if (this.enableSound) {
        this.playClickSound();
    }

    if(UserModel.getInstance().getTodayAdCount() >= ENV.MAX_AD_COUNT){
      GlobalEvent.emit(EventTypes.MAX_AD_COUNT_REACHED, "今日广告次数已达上限");
      return;
    }

    // 弹出激励广告
    TaKuSDK.getInstance().showRewardedVideoAd();

  }

  private videoPlayEnd(){
    this.startCountdown();
  }

  /**
   * 开始倒计时
   */
  private startCountdown() {
    // 显示初始倒计时
    this.countdownLabel.string = this.countdown.toString() + "S";
    this.countdownLabel.node.active = true;
    this.buttonNode.active = false;
    
    // 取消之前可能存在的定时器
    if (this.timerCallback) {
      this.unschedule(this.timerCallback);
    }
    
    // 创建新的定时器回调
    this.timerCallback = () => {
      this.countdown--;
      
      // 更新倒计时显示
      this.countdownLabel.string = this.countdown.toString() + "S";
      
      // 检查倒计时是否结束
      if (this.countdown <= 0) {
        // 重置倒计时 随机增加1-6秒
        this.countdown = this.maxCountdown + Math.floor(Math.random() * 6);
        // 显示按钮，隐藏倒计时
        this.buttonNode.active = true;
        this.countdownLabel.node.active = false;
        // 取消定时器
        this.unschedule(this.timerCallback);
        this.timerCallback = null;
      }
    };
    
    // 每秒执行一次回调
    this.schedule(this.timerCallback, 1);
  }

  /**
   * 停止倒计时
   */
  private stopCountdown() {
    if (this.timerCallback) {
      this.unschedule(this.timerCallback);
      this.timerCallback = null;
    }
  }

  private playClickSound() {
      if (this.audioClip) {
          this.audioSource?.playOneShot(this.audioClip);
          return;
      }

      if (!this.soundPath) return;

      resources.load(this.soundPath, AudioClip, (err, clip) => {
          if (err) {
              console.warn('[ShakeButton] Failed to load audio:', err);
              return;
          }
          this.audioClip = clip!;
          this.audioSource?.playOneShot(clip!);
      });
  }

  private startShake() {
      this.shakeTween = tween(this.buttonNode)
          .repeatForever(
              tween()
                  .to(0.1, { angle: 10 })
                  .to(0.1, { angle: -10 })
                  .to(0.1, { angle: 0 })
                  .delay(1)
          )
          .start();
  }

  private stopShake() {
      if (this.shakeTween) {
          this.shakeTween.stop();
          this.shakeTween = null;
      }
  }
}
